package com.kevin.fileproviderserver;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class FileSelectionActivity extends Activity {
	private ListView mlvFileList;
	private String[] mlsFileName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_select);
		
		mlvFileList = (ListView) findViewById(R.id.file_list);
		
		mlsFileName = ListFiles();
		mlvFileList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mlsFileName));
		
		mlvFileList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				File reqFile = new File(getFilesDir() + "/images/" + mlsFileName[position]);
				Uri sFileUri = FileProvider.getUriForFile(FileSelectionActivity.this,
						"com.kevin.FileProviderServer.FileProvider", reqFile);

				Intent intent = new Intent();
				intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				intent.setDataAndType(sFileUri, getContentResolver().getType(sFileUri));
				setResult(RESULT_OK, intent);
				
				finish();
			}
			
		});
	}

	private String[] ListFiles() {
		ArrayList<String> arrFiles = new ArrayList<String>();

		String sDirPath = getBaseContext().getFilesDir() + "/images";
		File file = new File(sDirPath);

		File[] files = file.listFiles();
		for (File file2 : files) {
			String sFileName = file2.getName();
			if (file2.isFile()) {
				arrFiles.add(sFileName);
			}
		}

		return (String[]) arrFiles.toArray(new String[]{});
	}
}
